<template>
  <div class="bom-container">
    <BasicInformation
      title="BOM管理"
      :primary-actions="actions"
      @action="handleAction"
    />

    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="120px"
    >
      <!-- 基础信息 -->
      <el-card class="form-section">
        <template #header>
          <span class="section-title">基础信息</span>
        </template>

        <el-row :gutter="30">
          <el-col :md="12">
            <el-form-item label="BOM名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入BOM名称"
                clearable
              />
            </el-form-item>
          </el-col>

          <el-col :md="12">
            <el-form-item label="主产品" prop="product">
              <good-selector v-model="form.product" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 原材料管理 -->
      <el-card class="form-section">
        <template #header>
          <div class="section-header">
            <span class="section-title">原材料清单</span>
            <el-button
              type="primary"
              size="small"
              @click="materialDialogVisible = true"
            >
              添加原材料
            </el-button>
          </div>
        </template>

        <el-table :data="form.material" border style="width: 100%">
          <el-table-column prop="code" label="物料编码" />
          <el-table-column prop="name" label="物料名称" />
          <el-table-column prop="kname" label="物料种类" />
          <el-table-column prop="uname" label="物料单位" />
          <el-table-column prop="tax" label="税率" />
        </el-table>
      </el-card>

      <!-- 物料选择对话框 -->
      <material-selector-dialog
        v-model:modelValue="form.material"
        v-model:visible="materialDialogVisible"
      />
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { BOM, Good } from '@/types/basic/BOM'
import BasicInformation from '@/public-view/BasicInformation.vue'
import GoodSelector from '@/basic-view/bom/GoodSelector.vue'
import MaterialSelectorDialog from '@/basic-view/bom/MaterialSelectorDialog.vue'
import request from '@/util/request'

const route = useRoute()
const router = useRouter()

const userInfo = sessionStorage.getItem('user');
const user = userInfo ? JSON.parse(userInfo) : null;

// 表单状态
const form = reactive<BOM>({
  id: 0,
  name: '',
  product: null,
  material: [],
  createUser: user.user.name,
  updateUser: user.user.name,
})

// 验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入BOM名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  product: [
    { required: true, message: '请选择主产品', trigger: 'change' }
  ]
})

// 弹窗控制
const materialDialogVisible = ref(false)

// 操作按钮
const actions = [
  { name: 'save', label: '保存BOM', type: 'primary' },
  { name: 'reset', label: '重置表单', type: 'warning' }
]

// 表单引用
const formRef = ref<FormInstance>()

// 获取路由 ID
const getValidId = () => {
  const raw = route.params.id
  const idStr = Array.isArray(raw) ? raw[0] : raw
  return Number(idStr) || 0
}

// 加载数据
async function loadData() {
  const id = getValidId()
  if (!id) {
    ElMessage.error('无效的BOM ID')
    router.push('BOMLimitPage')
    return
  }
  try {
    const resp = await request.post('basic/BOM/getBOMById', {
      params: { id }
    })
    if (Number(resp.data.code) === 200) {
      const data = resp.data.data
      form.id = data.id
      form.name = data.name
      form.product = data.product
      form.material = data.material
    } else {
      ElMessage.error(`加载失败：${resp.data.code}`)
    }
  } catch (err) {
    ElMessage.error('数据加载失败')
  }
}

// 监听路由变化
watch(
  () => route.params.id,
  (newId, oldId) => {
    if (newId !== oldId) loadData()
  }
)

// 初始化加载
onMounted(() => {
  loadData()
})

// 操作处理
function handleAction(action: string) {
  if (action === 'save') submitForm()
  else if (action === 'reset') resetForm()
}

// 提交表单到后端
async function submitForm() {
  try {
    await formRef.value?.validate()
    const payload: BOM = {
      ...form,
      material: form.material.map(m => ({
        id:   m.id,
        code: m.code,
        name: m.name,
        kid:  m.kid,
        uid:  m.uid,
        tax:  m.tax
      }))
    }
    const resp = await request.post('basic/BOM/updateBOM', payload)
    if (Number(resp.data.code) === 200) {
      ElMessage.success(resp.data.message || 'BOM 更新成功')
      router.push({ name: 'BOMLimitPage' })
    } else {
      ElMessage.error(resp.data.message || 'BOM 更新失败')
    }
  } catch (err) {
    ElMessage.error('网络或服务异常，BOM 保存失败')
  }
}

// 重置表单
function resetForm() {
  formRef.value?.resetFields()
  loadData()
  ElMessage.info('已重置表单')
}
</script>

<style scoped>
.bom-container { padding: 20px; }
.form-section { margin-bottom: 20px; }
.section-header { display: flex; justify-content: space-between; align-items: center; }
.section-title { font-size: 16px; font-weight: 600; }
</style>
